package com.example.myblog1_0.service.Impl;

import com.alibaba.fastjson.JSONObject;

import com.example.myblog1_0.service.AuthService;
import com.example.myblog1_0.service.DefaultAuthService;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import javax.xml.rpc.ServiceException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xc
 * @Date: 2018/11/8 16:12
 * @Description:
 **/
@Service
public class QqAuthServiceImpl extends DefaultAuthService implements AuthService {
    private org.slf4j.Logger logger = LoggerFactory.getLogger(QqAuthServiceImpl.class);
    /**
     * 一些固定属性配置
     */
    private final static String AUTHORIZATION_URL = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=%s&redirect_uri=%s&scope=%s";
    private final static String ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=%s&client_secret=%s&code=%s&redirect_uri=%s";
    private static final String OPEN_ID_URL = "https://graph.qq.com/oauth2.0/me?access_token=%s";
    private static final String USER_INFO_URL = "https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s";
    /**
     * 以下为QQ互联申请到的属性值
     */
    private  static final String CALLBACK_URL = "https://www.abstergo.xin/qq";
    private  static final String API_ID  = "101541695";
    private  static final String API_KEY = "7c9ad2ada7e4a3b8ba03d2a09fa4f04c";

    private  static final String SCOPE = "get_user_info";


    private Map<String,String> getParam(String string){
        Map<String,String> map = new HashMap<>();
        String[] kvArray = string.split("&");
        for (int i = 0; i < kvArray.length; i++) {
            String[] kv = kvArray[i].split("=");
            map.put(kv[0],kv[1]);
        }
        return map;
    }
    /**
     * 根据code获得accessToken
     *
     * @param code qq授权后会返回一个对应的code值
     * @return
     * @throws ServiceException
     */
    @Override
    public String getAccessToken(String code) throws ServiceException {
        String url = String.format(ACCESS_TOKEN_URL,API_ID,API_KEY,code,CALLBACK_URL);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();
        /**
         * 从uri链接中获得access_token属性
         */
        String resp = getRestTemplate().getForObject(uri,String.class);
        logger.error("getAccessToken resp = "+resp);
        if (resp.contains("access_token")){
            Map<String,String> map = getParam(resp);
            String access_token = map.get("access_token");
            System.out.println(access_token);
            return access_token;
        }else {
            throw new ServiceException(resp);
        }
    }
    /**
     * QQ接口返回类型是text/plain，此处将其转为json
     */
    public JSONObject convertToJson(String string){
        string = string.substring(string.indexOf("(")+1,string.length());
        string = string.substring(0,string.indexOf(")"));
        logger.error("convertToJson s = "+string);
        JSONObject jsonObject = JSONObject.parseObject(string);
        return jsonObject;
    }
    /**
     * 获得openid
     *
     * @param accessToken
     * @return
     * @throws ServiceException
     */
    @Override
    public String getOpenId(String accessToken) throws ServiceException {
        String url = String.format(OPEN_ID_URL,accessToken);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        String resp = getRestTemplate().getForObject(uri,String.class);
        logger.error("getOpenId resp = "+resp);
        if (resp.contains("openid")){
            JSONObject jsonObject = convertToJson(resp);
            String openid = jsonObject.getString("openid");
            return openid;
        }else {
            throw new ServiceException(resp);
        }
    }

    /**
     * accessToken到期之后重新刷新
     *
     * @param code
     * @return
     */
    @Override
    public String refreshToken(String code) {
        return null;
    }

    /**
     * 跳转链接
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    public String getAuthorizationUrl() throws UnsupportedEncodingException {
        String uri = String.format(AUTHORIZATION_URL,API_ID,CALLBACK_URL,SCOPE);
        return uri;
    }

    /**
     * 获得qq用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     * @throws ServiceException
     */
    @Override
    public JSONObject getUserInfo(String accessToken, String openId) throws ServiceException {
        openId = getOpenId(accessToken);
        String url = String.format(USER_INFO_URL,accessToken,API_ID,openId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        String resp = getRestTemplate().getForObject(uri,String.class);
        logger.error("getOpenId resp = "+resp);

        JSONObject data = JSONObject.parseObject(resp);
        logger.error("resp = " + data);
        JSONObject result = new JSONObject();
        result.put("nickname",data.getString("nickname"));
        result.put("id",openId);
        result.put("avatar",data.getString("figureurl_qq_1"));

        return result;
    }
}
